package com.todod.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.todod.common.util.MinIoUtils;
import com.todod.common.util.ZipCompress;
import com.todod.dto.PublicFileDto;
import com.todod.entity.ResultData;
import com.todod.mapper.CatalogDetailMapper;
import com.todod.mapper.PublicCatalogMapper;
import com.todod.mapper.PublicFileCollectMapper;
import com.todod.model.CatalogDetail;
import com.todod.model.PublicCatalog;
import com.todod.model.PublicFile;
import com.todod.model.PublicFileShare;
import com.todod.model.User;
import com.todod.service.ICatalogDetailService;
import com.todod.service.IUserService;
import com.todod.service.PublicCatalogService;
import com.todod.service.PublicFileService;
import com.todod.service.PublicFileShareService;

/**
 * @author lql
 * @date 2020年12月25日
 */
@RestController
@RequestMapping("/publicCatalog")
public class PublicCatalogController extends BaseManageController {

	@Autowired
	public PublicCatalogService publicCatalogService;
	@Autowired
	public PublicCatalogMapper publicCatalogMapper;
	@Autowired
	private PublicFileService publicFileService;
	@Autowired
	private IUserService iUserService;
	@Autowired
	private PublicFileShareService publicFileShareService;
	@Autowired
	private PublicFileCollectMapper publicFileCollectMapper;

	// 存储桶名称
	@Value("${minio.bucketName}")
	private String bucketName;
	@Autowired
	private MinIoUtils minIoUtils;
	@Autowired
	public CatalogDetailMapper catalogDetailMapper;
	@Autowired
	public ICatalogDetailService catalogDetailService;

	/**
	 * 
	 * @param _userId
	 * @param reqPublicCatalog
	 * @return
	 */
	@PostMapping("/save")
	public ResultData saveData(@RequestAttribute Long _userId, @RequestBody PublicCatalog publicCatalog) {

		if (publicCatalog.getId() != null) {
			try {
				publicCatalogService.editData(_userId, publicCatalog);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				return ResultData.error(e.toString().substring(20));
			}
		} else {
			try {
				User user = iUserService.getById(_userId);
				publicCatalog.setDepartmentId(user.getDepartid());

				publicCatalogService.saveData(_userId, publicCatalog);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				return ResultData.error(e.toString().substring(20));
			}
		}

		return ResultData.success();
	}

	/**
	 * 
	 * @param _userId
	 * @param reqPublicCatalog
	 * @return
	 */
	@PostMapping("/edit")
	public ResultData editData(@RequestAttribute Long _userId, @RequestBody PublicCatalog publicCatalog) {
		try {
			User user = iUserService.getById(_userId);
			publicCatalog.setDepartmentId(user.getDepartid());

			publicCatalogService.editData(_userId, publicCatalog);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return ResultData.error(e.toString().substring(20));
		}
		return ResultData.success();
	}

	/**
	 * 
	 * @param _userId
	 * @param PublicCatalog
	 * @return
	 */
	@PostMapping("/copy")
	public ResultData copyData(@RequestAttribute Long _userId, @RequestBody PublicCatalog publicCatalog) {
		try {
			User user = iUserService.getById(_userId);
			publicCatalog.setDepartmentId(user.getDepartid());

			publicCatalogService.copyData(_userId, publicCatalog);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return ResultData.error(e.toString().substring(20));
		}
		return ResultData.success();
	}

	/**
	 * 
	 * @param _userId
	 * @param PublicCatalog
	 * @return
	 */
	@PostMapping("/move")
	public ResultData moveData(@RequestAttribute Long _userId, @RequestBody PublicCatalog publicCatalog) {
		try {
			User user = iUserService.getById(_userId);
			publicCatalog.setDepartmentId(user.getDepartid());

			publicCatalogService.moveData(_userId, publicCatalog);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return ResultData.error(e.toString().substring(20));
		}
		return ResultData.success();
	}

	/**
	 * @title deleteInLogic
	 * @description 逻辑删除
	 * @param _userId
	 * @param ids
	 * @param status(-1:删除 ;1:使用)
	 * @return
	 */
	@PostMapping("/deleteInLogic")
	public ResultData deleteInLogic(@RequestAttribute Long _userId, String ids, String status) {
		String[] split = ids.split(",");
		for (String s : split) {
			Long id = Long.valueOf(s);
			PublicCatalog publicCatalog = publicCatalogMapper.selectById(id);
			if (publicCatalog != null) {
				Map<String, Object> map = publicCatalogService.getChildren(publicCatalog.getId());
				if (map != null && map.size() > 0) {
					return ResultData.error("当前目录下存在子目录或文件，请先删除子文件！");
				} else {
					publicCatalogService.deleteInLogic(_userId, id, status);
				}
			} else {
				publicCatalogService.deleteInLogic(_userId, id, status);
			}
		}

		return ResultData.success();
	}

	/**
	 * @title deleteAllInCatalogOrFile
	 * @description 物理删除
	 * @param _userId
	 * @param ids
	 * @return
	 */
	@PostMapping("/deleteAllInCatalogOrFile")
	public ResultData deleteAllInCatalogOrFile(@RequestAttribute Long _userId, String ids) {
		String[] split = ids.split(",");
		for (String s : split) {
			Long id = Long.valueOf(s);
			publicCatalogService.deleteAllInCatalogOrFile(_userId, id);
		}

		return ResultData.success();
	}

	/**
	 * 
	 * @param ids
	 * @return
	 */
	@PostMapping("/delete")
	public ResultData delete(String code) {// 源数据
		PublicCatalog publicCatalog = publicCatalogMapper.selectById(code);
		if (publicCatalog != null) {
			Map<String, Object> map = publicCatalogService.getChildren(publicCatalog.getId());
			if (map != null && map.size() > 0) {
				return ResultData.error("当前目录下存在子目录或文件，请先删除子文件！");
			} else {
				publicCatalogMapper.deleteById(code);
				return ResultData.success();
			}
		}
		return null;
	}

	/**
	 * 
	 * @param code
	 * @return
	 */
	@GetMapping("/getInfo")
	public ResultData getInfo(Long code) {
		if (code == null) {
			return ResultData.error(ResultData.PARAM_ERROR_CODE, "参数错误");
		}
		return ResultData.success("ok", publicCatalogService.getInfo(code));
	}

	/**
	 * @Title: getLeafNode
	 * @Description: 获取全部叶子节点
	 * @author dyl
	 * @date: 2021-01-28
	 * @return
	 * @return Result
	 */
	@GetMapping("/getAllLeafNode")
	public ResultData getAllLeafNode(@RequestAttribute Long _userId) {
		User user = iUserService.getById(_userId);
		// 获取公共数据
		List<PublicCatalog> list = publicCatalogService.getListByFlag("M");

		// 获取个人创建数据
		List<PublicCatalog> plist = publicCatalogService.getListByParentId(user.getDepartid(), _userId);

		if (plist != null && plist.size() > 0) {
			list.addAll(plist);
		}
		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param _userId
	 * @return
	 */
	@RequestMapping("/getTreeListInAuthority")
	public ResultData getTreeListInAuthority(@RequestAttribute Long _userId) {
		// 获取权限数据
		List<PublicCatalog> list = publicCatalogService.getListInAuthorityByUserIdAndType(_userId, "M");
		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectFile
	 * @return
	 */
	@RequestMapping("/getTreeList2")
	public ResultData getTreeList2(@RequestAttribute Long _userId) {

		User user = iUserService.getById(_userId);

		// 初始化数据
		List<PublicCatalog> listShare = new ArrayList<PublicCatalog>();
		List<String> names = new ArrayList<String>();
		// 获取个人创建数据
		List<PublicCatalog> plist = publicCatalogService.getListByParentId(user.getDepartid(), _userId);
		// 获取分享的文档
		List<PublicFileShare> listInAuthority = publicFileShareService.getFileAuthorityByUserId(_userId);
		if (listInAuthority != null && listInAuthority.size() > 0) {
			PublicCatalog publicCatalog = new PublicCatalog();
			publicCatalog.setId(2L);
			publicCatalog.setParentId(1L);
			publicCatalog.setSortNum(0);
			publicCatalog.setTypeName("共享文档");
			publicCatalog.setFlag("U");
			publicCatalog.setState("1");
			publicCatalog.setDepartmentId(user.getDepartid());
			publicCatalog.setShareFlag("1");
			listShare.add(publicCatalog);

			for (PublicFileShare publicFileShare : listInAuthority) {
				PublicCatalog publicCatalog1 = publicCatalogMapper.selectById(publicFileShare.getFileId());
				if (publicCatalog1 != null) {
					String level = publicCatalog1.getLevels();
					String[] levels = level.split(";");

					for (int i = 0; i < levels.length; i++) {
						if (i == 0) {
							PublicCatalog publicCatalog2 = publicCatalogMapper.selectById(levels[i]);
							publicCatalog2.setParentId(2L);
							publicCatalog2.setShareFlag("1");

							if (!names.contains(publicCatalog2.getId().toString())) {
								names.add(String.valueOf(publicCatalog2.getId()));
								listShare.add(publicCatalog2);
							}
						} else {
							PublicCatalog publicCatalog2 = publicCatalogMapper.selectById(levels[i]);
							publicCatalog2.setShareFlag("1");

							if (!names.contains(publicCatalog2.getId().toString())) {
								names.add(String.valueOf(publicCatalog2.getId()));
								listShare.add(publicCatalog2);
							}
						}
					}

					if (!names.contains(publicCatalog1.getId().toString())) {
						names.add(String.valueOf(publicCatalog1.getId()));
						publicCatalog1.setShareFlag("1");
						listShare.add(publicCatalog1);
					}
				}

				PublicFile publicFile = publicFileService.selectByCodeInUse(publicFileShare.getFileId());
				if (publicFile != null) {
					String level1 = publicFile.getLevel();
					String[] levels1 = level1.split(";");

					PublicCatalog publicCatalog2 = publicCatalogMapper.selectById(levels1[0]);
					for (int i = 1; i < levels1.length; i++) {
						PublicCatalog publicCatalog3 = publicCatalogMapper.selectById(levels1[i]);
						publicCatalog3.setShareFlag("1");

						if (!names.contains(publicCatalog3.getId().toString())) {
							names.add(String.valueOf(publicCatalog3.getId()));
							listShare.add(publicCatalog3);
						}
					}

					if (!names.contains(publicCatalog2.getId().toString())) {
						names.add(String.valueOf(publicCatalog2.getId()));
						publicCatalog2.setParentId(2L);
						publicCatalog2.setShareFlag("1");
						listShare.add(publicCatalog2);
					}
				}

			}
		}
		// 获取分享的文档
		List<PublicFileDto> listCollect = publicFileCollectMapper.getListByUserId(_userId);
		if (listCollect != null && listCollect.size() > 0) {
			PublicCatalog publicCatalog = new PublicCatalog();
			publicCatalog.setId(3L);
			publicCatalog.setParentId(1L);
			publicCatalog.setSortNum(0);
			publicCatalog.setTypeName("我的收藏");
			publicCatalog.setFlag("SC");
			publicCatalog.setState("1");
			publicCatalog.setDepartmentId(user.getDepartid());
			publicCatalog.setShareFlag("2");

			listShare.add(publicCatalog);
		}
		plist.addAll(listShare);
		return ResultData.success("ok", plist);
	}

	/**
	 * @title getTreePersonalList
	 * @description 获取个人创建数据
	 * @param companyId
	 * @param _userId
	 * @param request
	 * @param queryProjectFile
	 * @return
	 */
	@RequestMapping("/getTreePersonalList")
	public ResultData getTreePersonalList(@RequestAttribute Long _userId) {
		User user = iUserService.getById(_userId);

		List<PublicCatalog> plist = publicCatalogService.getListByParentId(user.getDepartid(), _userId);
		return ResultData.success("ok", plist);
	}

	/**
	 * @Title: downLoad
	 * @Description: 附件下载
	 * @author lql
	 * @return
	 * @date 2021年3月1日
	 * @return ResponseEntity响应的头文件信息，具体信息
	 * @throws Exception
	 */
	@RequestMapping(value = "/downLoad", method = RequestMethod.POST, produces = "application/json")
	public void downLoad(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") String id,
			@RequestParam("type") String type) throws Exception {

		String typeName = "";
		Map<String, Object> map = new HashMap<>();

		if (type.equalsIgnoreCase("M")) {
			CatalogDetail catalogDetail = catalogDetailMapper.selectById(Long.valueOf(id));
			typeName = catalogDetail.getTypeName();
			map = catalogDetailService.getOnlyChildren(catalogDetail.getId());
		} else {
			PublicCatalog publicCatalog = publicCatalogMapper.selectById(Long.valueOf(id));
			typeName = publicCatalog.getTypeName();
			map = publicCatalogService.getOnlyChildren(publicCatalog.getId());
		}

		String path = ResourceUtils.getURL("classpath:").getPath() + File.separator + "static" + File.separator + "zip";

		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		List<InputStream> ins = new ArrayList<InputStream>();
		List<String> fileNames = new ArrayList<>();

		for (Map.Entry<String, Object> entry : map.entrySet()) {
			if (entry.getKey().equalsIgnoreCase("listFile")) {
				List<PublicFile> listFile = (List<PublicFile>) entry.getValue();
				listFile.forEach(y -> {
					String string = y.getRelativePath();
					String originalName = y.getOriginalName();
					String fileName = string.substring(string.indexOf("/") + 1);

					minIoUtils.download(response, bucketName, fileName, originalName);
					String abstractPath = minIoUtils.getObjectUrl(bucketName, fileName, 7);
					InputStream input;
					URL url;
					try {
						url = new URL(abstractPath);
						input = url.openStream();
						fileNames.add(originalName);
						ins.add(input);
					} catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				});
			} else if (entry.getKey().equalsIgnoreCase("children")) {
				Map<String, Object> map1 = (Map<String, Object>) entry.getValue();
				for (Map.Entry<String, Object> entry1 : map1.entrySet()) {
					if (entry1.getKey().equalsIgnoreCase("listFile")) {
						List<PublicFile> listFile = (List<PublicFile>) entry1.getValue();
						listFile.forEach(y -> {
							String string = y.getRelativePath();
							String originalName = y.getOriginalName();
							String fileName = string.substring(string.indexOf("/") + 1);

							minIoUtils.download(response, bucketName, fileName, originalName);
							String abstractPath = minIoUtils.getObjectUrl(bucketName, fileName, 7);
							InputStream input;
							URL url;
							try {
								url = new URL(abstractPath);
								input = url.openStream();
								fileNames.add(originalName);
								ins.add(input);
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						});
					}
				}
			}

		}
		String filename = "download";
		response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
		response.setHeader("Content-Disposition",
				"attachment; filename=" + URLEncoder.encode(filename, "UTF-8") + ".zip");
		response.setHeader("Content-Type", "application/zip");

		ZipCompress.compressByFiles1(ins, response.getOutputStream(), fileNames, typeName);
	}

	@RequestMapping("/test")
	public ResultData test(@RequestAttribute Long _userId) {

		Map<String, Object> map = publicCatalogService.getChildren(_userId);

		return ResultData.success("ok", map);
	}

	/**
	 * 
	 * @param _userId
	 * @return
	 */
	@RequestMapping("/getInitialLoading")
	public ResultData getInitialLoading(@RequestAttribute Long _userId) {
		User user = iUserService.getById(_userId);
		// 获取权限数据
		List<PublicCatalog> list = publicCatalogService.getListByUserIdAndType(_userId, "M", user.getDepartid());
		return ResultData.success("ok", list);
	}

	/**
	 * 
	 * @param _userId
	 * @return
	 */
	@RequestMapping("/getAgainLoading")
	public ResultData getAgainLoading(@RequestAttribute Long _userId, Long parentId) {
		User user = iUserService.getById(_userId);
		// 获取权限数据
		List<PublicCatalog> list = publicCatalogService.getListByUserIdAndTypeAndParentId(_userId, "M",
				user.getDepartid(), parentId);
		return ResultData.success("ok", list);
	}

}
